import random
import re
from flask import current_app, jsonify, request, Blueprint

import utils
from app import redis_client, LogService
from presenter import MobileCodePresenter
from utils import create_response, StateCode

key = current_app.config['SECRET_KEY']
mobile_bp = Blueprint('mobile_server', __name__)


@mobile_bp.route('/mobile/get_verify_code', methods=['POST'])
# 发送一次性密码（验证码）
def getVerifyCode():
    mobile_no = request.json.get('mobileNo')
    if not utils.checkMobile(mobile_no):
        return jsonify(create_response(StateCode.MOBILE_ERROR)), 400
    sent_code = getVerificationCode(mobile_no)
    mobile_present = MobileCodePresenter(sent_code).as_dict()
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=mobile_present)), 200


@mobile_bp.route('/mobile/check', methods=['POST'])
def checkMobile():
    pattern = r'^1[3-9]\d{9}$'
    number = request.json.get('mobileNo')
    state = {
        "result": bool(re.match(pattern, number))
    }
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=state)), 200


def getVerificationCode(mobile_no):
    verification_code = generateRandomNumber()  # 生成验证码
    if redis_client.set(mobile_no, verification_code, 300):
        return verification_code
    else:
        print(f"{redis_client.client}")


# 生成6位随机数字
def generateRandomNumber(length=6):
    # 确保生成的数字至少有6位，即使前几位是0
    number = random.randint(10 ** (length - 1), 10 ** length - 1)
    return number
